package cn.edu.dyxy.dao;

import cn.edu.dyxy.entity.Book;
import cn.edu.dyxy.utils.DBUtils;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author JokerQiu
 * @date 2021年12月23日 15:28
 */

public class BookDao {
    /**
     * 获取图书列表
     *
     * @return
     * @throws SQLException
     */
    public List<Book> getBookList() throws SQLException {
        //连接数据库
        Connection connection = DBUtils.getConntect();
        //创建statment对象
        Statement statement = connection.createStatement();
        String sql = "select * from t_book";
        //执行sql，获得结果集
        ResultSet resultSet = statement.executeQuery(sql);
        //创建列表，存储所有的图书信息
        List<Book> bookList = new ArrayList<>();
        //处理结果集
        while (resultSet.next()) {
            Book book = new Book();
            book.setId(resultSet.getInt("id"));
            book.setProductName(resultSet.getString("product_name"));
            book.setFixedPrice(resultSet.getDouble("fixed_price"));
            book.setDangPrice(resultSet.getDouble("dang_price"));
            book.setProductPic(resultSet.getString("product_pic"));
            book.setAuthor(resultSet.getString("author"));
            book.setPublishing(resultSet.getString("publishing"));
            //简单的日期格式化
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //获取数据库中的发布时间
            String publishTime = resultSet.getString("publish_time");
            //转换成long值
            Long publishTimeLong = Long.parseLong(publishTime);
            //创建时间
            Date date = new Date(publishTimeLong);
            //格式化时间
            String formatDate = sdf.format(date);
            book.setPublishTime(formatDate);
            book.setAuthorSummary(resultSet.getString("author_summary"));
            book.setDescription(resultSet.getString("description"));
            book.setScore(resultSet.getInt("score"));
            //把一本书加入到booklist中
            bookList.add(book);
        }
        //关闭连接
        DBUtils.close(resultSet, statement, connection);
        return bookList;
    }

    public Book getBookById(String bookId) throws SQLException {
        Connection connection = DBUtils.getConntect();
        String sql = "select id,product_name,fixed_price,dang_price " +
                "from t_book where id=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, bookId);
        ResultSet resultSet = ps.executeQuery();
        Book book = new Book();
        while (resultSet.next()) {
            book.setId(resultSet.getInt("id"));
            book.setProductName(resultSet.getString("product_name"));
            book.setFixedPrice(resultSet.getDouble("fixed_price"));
            book.setDangPrice(resultSet.getDouble("dang_price"));
        }
        DBUtils.close(resultSet, ps, connection);
        return book;
    }

}
